package hamburgerwang.businfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class BusInfoQuery extends Activity {

	private ProgressDialog mProgressDialog;
	private Thread mThread;
	private boolean mConfirmed;
	private int mInteractionCount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// 检测网络连接
		ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo network = manager.getActiveNetworkInfo();
		if (network == null || !network.isAvailable()) {
			startActivity(new Intent(
					android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			this.finish();
		}

		mConfirmed = false;
		mInteractionCount = 0;

		final Button btnQueryStop = (Button) findViewById(R.id.ButtonQueryStop);
		final Button btnLineRoutine = (Button) findViewById(R.id.ButtonLineRoutine);
		final Button btnQueryDistance = (Button) findViewById(R.id.ButtonDistance);
		final EditText txtBusStop = (EditText) findViewById(R.id.EditTextBusStop);
		final Spinner cboBusStop = (Spinner) findViewById(R.id.SpinnerBusStop);
		final Spinner cboBusLine = (Spinner) findViewById(R.id.SpinnerBusLine);
		final TextView txtDistance = (TextView) findViewById(R.id.TextViewDistance);

		mProgressDialog = new ProgressDialog(BusInfoQuery.this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 设置旋转的圆形风格
		mProgressDialog.setMessage(getResources().getString(
				R.string.waiting_message)); // 设置 提示信息
		mProgressDialog.setIndeterminate(true); // 设置进度条是否不明确
		mProgressDialog.setCancelable(true); // 设置是否可以按退回按键取消
		mProgressDialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				if (mThread != null && !mThread.isInterrupted()){
					mThread.interrupt();
				}
			}
		});
		
		btnQueryStop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mProgressDialog.show();
				mThread = new Thread(new Runnable() {

					@Override
					public void run() {
						busLines = null;
						busStops = null;
						try {
							IQueryHelper queryHelper = QueryHelperFactory
									.createQueryHelper();
							if (SettingsDialog.getProxySet(BusInfoQuery.this)) {
								QueryHelperFactory
										.setProxy(
												SettingsDialog
														.getProxyHost(BusInfoQuery.this),
												SettingsDialog
														.getProxyPort(BusInfoQuery.this));
							}else{
								QueryHelperFactory.setProxy("", 0);
							}
							busLines = queryHelper.QueryLines(txtBusStop
									.getText().toString());
							busStops = queryHelper.QueryStops(txtBusStop
									.getText().toString());
							handler.sendEmptyMessage(0);
						} catch (Exception ex) {
							Message msg = new Message();
							msg.what = 1;
							Bundle bundle = new Bundle();
							bundle.putString("Message", ex.getMessage());
							msg.setData(bundle);
							handler.sendMessage(msg);
						}
					}
				});
				mThread.start();
			}

			private BusLine[] busLines;
			private BusStop[] busStops;
			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (mProgressDialog != null) {
						mProgressDialog.dismiss();
					}
					if (msg.what == 0) {// 成功
						if (busLines != null) {
							ArrayAdapter<BusLine> lineAdapter = new ArrayAdapter<BusLine>(
									BusInfoQuery.this, R.layout.other, busLines);
							lineAdapter
									.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							cboBusLine.setAdapter(lineAdapter);
						}
						if (busStops != null) {
							ArrayAdapter<BusStop> adapter = new ArrayAdapter<BusStop>(
									BusInfoQuery.this, R.layout.other, busStops);
							adapter
									.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							cboBusStop.setAdapter(adapter);
						}
					} else {
						BusInfoQuery.this.showMessage(msg, true);
					}
				}
			};

		});

		cboBusStop.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Spinner cboBusStop = (Spinner) parent;
				BusStop stop = (BusStop) cboBusStop.getSelectedItem();
				txtDistance.setText(stop.Description);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				txtDistance.setText("");
			}
		});

		cboBusLine.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				BusLine line = (BusLine) cboBusLine.getSelectedItem();
				txtDistance.setText(line.Description);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				txtDistance.setText("");
			}

		});

		btnQueryDistance.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mProgressDialog.show();
				mThread = new Thread(new Runnable() {
					@Override
					public void run() {
						info = null;
						BusLine line = (BusLine) cboBusLine.getSelectedItem();
						BusStop stop = (BusStop) cboBusStop.getSelectedItem();
						if (stop != null && line != null) {
							try {
								IQueryHelper queryHelper = new hamburgerwang.suzhoubus.SuzhouQueryHelper();
								info = queryHelper.QueryRealTimeInfo(stop.ID,
										line.No);
								handler.sendEmptyMessage(0);
							} catch (Exception ex) {
								Message msg = new Message();
								msg.what = 1;
								Bundle bundle = new Bundle();
								bundle.putString("Message", ex.getMessage());
								msg.setData(bundle);
								handler.sendMessage(msg);
							}
						}
					}
				});
				mThread.start();
			}

			private String info;
			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					mThread = null;
					if (mProgressDialog != null) {
						mProgressDialog.dismiss();
					}
					txtDistance.setText("");
					if (msg.what == 0) {
						if (info != null) {
							txtDistance.setText(info);
						}
					} else {
						BusInfoQuery.this.showMessage(msg, true);
					}
				}
			};

		});

		btnLineRoutine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (cboBusLine.getSelectedItem() != null) {
					BusLine busLine = (BusLine) cboBusLine.getSelectedItem();
					final String[] routine = busLine.Routine;
					AlertDialog.Builder builder = new AlertDialog.Builder(
							BusInfoQuery.this);
					builder.setTitle(getResources().getString(
							R.string.line_routine_dialog_name, busLine.No));
					builder.setItems(routine,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									txtBusStop.setText(routine[which]
											.replaceAll("[\\(（].*[）\\)]", ""));
								}
							});

					AlertDialog dialog = builder.create();
					dialog.show();
				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (!mConfirmed) {
				Toast.makeText(this, R.string.press_again_to_exit,
						Toast.LENGTH_SHORT).show();
				mConfirmed = true;
				mInteractionCount = 0;
			} else {
				this.finish();
			}
			return true;

		default:
			return false;
		}
	}

	@Override
	public void onUserInteraction() {
		super.onUserInteraction();
		if (mInteractionCount > 1) {
			mConfirmed = false;
		}
		mInteractionCount++;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuSetting:
			Intent intent = new Intent(this, SettingsDialog.class);
			startActivity(intent);
			break;
		case R.id.menuAbout:
			this.showMessage(R.string.about_menu_content, true);
			break;
		default:
			return false;
		}
		return true;
	}

	private void showMessage(int resourceId, boolean longTime) {
		Toast.makeText(this, resourceId,
				longTime ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}

	private void showMessage(Message msg, boolean longTime) {
		Toast.makeText(this, msg.getData().getString("Message"),
				longTime ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}

}